<?php

namespace app\enterprise\controller;

use app\enterprise\model\disclose\DiscloseType as DiscloseTypeModel;
use app\enterprise\model\disclose\Disclose;

class DiscloseType extends Enterprise
{





    public function list()
    {

        $page = input('page', 1);
        $size = input('size', 10);
        $type_name = input('type_name', '');
        $where[] = ['status', '=', 1];
        $where[] = ['company_id', '=', $this->adminId];

        if ($type_name) {
            $where[] = ['type_name', 'like', '%'.$type_name.'%'];
        }
        if ($size) {
            $types = DiscloseTypeModel::where($where)->order('sort', 'desc')->paginate($size);
            return app('json')->success([
                'list'=>$types->items(),
                'total'=>$types->total(),
                'total_page'=>$types->lastPage(),
            ]);
        } else {
            $types = DiscloseTypeModel::where($where)->order('sort', 'desc')->select();
            return app('json')->success([
                'list'=>$types,
            ]);
        }
    }


    public function save()
    {
        $type_name = input('type_name', '');

        $sort = input('sort', 0);

        if (empty($type_name)) {
            return app('json')->fail('请输入类型名称');
        }

        $id = input('id', '');

        if (!$id) {
            DiscloseTypeModel::create([
                'type_name'=>$type_name,
                'sort'=>$sort,
                'company_id'=>$this->adminId,
            ]);
        } else {
            $model = DiscloseTypeModel::getOne($id);
            if (empty($model)) {
                return app('json')->fail('要操作的数据不存在');
            }
            if ($model['company_id'] != $this->adminId) {
                return app('json')->fail('您没有权限操作该数据');
            }
            $model->save([
                'type_name'=>$type_name,
                'sort'=>$sort,
            ]);
        }

        return app('json')->success('操作成功');
    }

    public function info()
    {
        $id = input('id', '');
        $model = DiscloseTypeModel::getOne($id);
        return app('json')->success([
            'info'=>$model,
        ]);
    }

    public function delete()
    {
        $id = input('id', '');
        $model = DiscloseTypeModel::getOne($id);
        if (!$model) {
            return app('json')->fail('数据不存在');
        }
        if ($model->company_id != $this->adminId) {
            return app('json')->fail('无权操作此数据');
        }
        // 判断是否有使用
        if (Disclose::where('type_id', $id)->where('status', 1)->find()) {
            return app('json')->fail('该类型已经被使用，不能删除');
        }

        DiscloseTypeModel::dataDelete($id);

        return app('json')->success('删除成功');

    }


}